#!/usr/bin/env python3
#coding: utf-8 
# @Time    : 2024-1-18
# @Author  : sdy
# @File    : log.py
import os
import sys
import time
import traceback
from functools import wraps

def log_output(log_path):
    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            try:
                stack = traceback.extract_stack()
                for trace in stack:
                    if trace[2] == '<module>':
                        caller_script = str(trace[0]).split(".")[0] .split("/")[-1]
                        break
                timestamp = time.strftime("%Y%m%d", time.localtime())
                log_file = os.path.join(log_path, f"{caller_script}_{timestamp}.log")
                with open(log_file, 'a') as log:
                    old_out = sys.stdout
                    sys.stdout = log
                    result = func(*args, **kwargs)
                    log.write(f"###########################[{time.strftime('%Y-%m-%d %H:%M:%S')}]###########################\n")
                    sys.stdout = old_out
                    return result
            except Exception as e:
                traceback.print_exc()
                raise e
        return inner
    return wrapper
